package com.jzg.jcptadmin.app;

import android.app.Application;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.multidex.MultiDex;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.core.ImagePipelineConfig;
import com.github.pwittchen.reactivenetwork.library.ConnectivityStatus;
import com.github.pwittchen.reactivenetwork.library.ReactiveNetwork;
import com.jzg.jcptadmin.R;
import com.jzg.jcptadmin.Utils.MyToast;
import com.jzg.jcptadmin.constant.Constant;
import com.jzg.jcptadmin.data.local.ACache;
import com.jzg.jcptadmin.data.network.HttpService;
import com.jzg.jcptadmin.data.vo.StatusData;
import com.jzg.jcptadmin.data.vo.User;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.orhanobut.logger.AndroidLogTool;
import com.orhanobut.logger.Logger;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.ResponseBody;

import java.io.File;
import java.io.IOException;

import cat.ereza.customactivityoncrash.CustomActivityOnCrash;
import cn.jpush.android.api.JPushInterface;
import retrofit.GsonConverterFactory;
import retrofit.Retrofit;
import retrofit.RxJavaCallAdapterFactory;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by jzg on 2015/12/22.
 */


public class AppContext extends Application {

    //车辆参配base地址
    public static final String BASE_URL = "http://192.168.0.140:8868";

    //线上环境
    //private static final String API = "http://jiance.jingzhengu.com";
    private static final String CITY_API = "http://ptvapi.guchewang.com";//线上城市

    //private static final String GLOBAL_API = "http://jiance.jingzhengu.com";//线上车型库
    private static final String GLOBAL_API = "http://jiancepgs.sandbox.guchewang.com";//沙盒车型库
    //线下测试
    private static final String API_CAR_CONFIG = "http://192.168.0.140:8081";
    //临时线下
    private static final String API = "http://192.168.0.140:8003";
    //沙盒环境
    //private static final String API = "http://jiancepgs.sandbox.guchewang.com";
    public static HttpService httpService;
    public static HttpService CarParamhttpService;
    public static HttpService CarConfighttpService;
    public static HttpService globalHttpService;
    public static HttpService cityHttpService;
    public static boolean isNetWork = true;//true有网
    public static int isWifi = 0;
    public DisplayImageOptions options;
    public String rootPath = Environment.getExternalStorageDirectory().getAbsolutePath() +
            File.separator + "JZGErShouChe";
    private static AppContext instance;
    private User user;
    private StatusData ss;

    public static AppContext getContext() {
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
//        LeakCanary.install(this);

        instance = this;
        // 初始化imageload库

        // 初始化 ACRA
//        ACRA.init(this);
//        SugarContext.init(this);
        //初始化Logger日志
        Logger.init("AppContext")
                .methodCount(3)                 // default 2
                .logTool(new AndroidLogTool()); // custom log tool, optional

        MultiDex.install(this);
        CustomActivityOnCrash.install(this);

//        //初始化网络框架
//         initHttp();
//         initCityHttp();
//         initGlobalHttp();

        initImageLoader();

        initHttp();
        initCarParamHttp();
        initCityHttp();
        initGlobalHttp();
        initCarConfigHttp();

        initNet();
        JPushInterface.setDebugMode(false);    // 设置开启日志,发布时请关闭日志
        JPushInterface.init(this);            // 初始化 JPush


        //Fresco
        ImagePipelineConfig imagePipelineConfig = ImagePipelineConfig.newBuilder(this)
                .setDownsampleEnabled(true)
                .build();
        Fresco.initialize(this, imagePipelineConfig);
    }

    public void initNet() {
        ReactiveNetwork reactiveNetwork = new ReactiveNetwork();
        reactiveNetwork.observeConnectivity(this)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<ConnectivityStatus>() {
                    @Override
                    public void call(ConnectivityStatus connectivityStatus) {
//                        Logger.d(connectivityStatus.toString());
//                        Logger.e(ConnectivityStatus.OFFLINE.toString());
                        if (connectivityStatus.toString().equals(ConnectivityStatus.OFFLINE.toString()) || connectivityStatus.toString()
                                .equals(ConnectivityStatus.WIFI_CONNECTED_HAS_NO_INTERNET.toString())) {
                            MyToast.showShort(Constant.errr_net);
                            isNetWork = false;
                        } else {
                            isNetWork = true;
                        }

                        if (connectivityStatus.toString().equals(ConnectivityStatus.WIFI_CONNECTED.toString())
                                && connectivityStatus.toString().equals(ConnectivityStatus.WIFI_CONNECTED_HAS_NO_INTERNET.toString())) {
                            //连接了无线,且无线不能用
                            isWifi = 1;
                        } else if (connectivityStatus.toString().equals(ConnectivityStatus.OFFLINE.toString())) {
                            //网络不可用
                            isWifi = 1;
                        } else if (connectivityStatus.toString().equals(ConnectivityStatus.MOBILE_CONNECTED.toString())) {
                            //连接了移动网络
                            isWifi = 2;
                        } else {
                            isWifi = 0;
                        }
//                        bt_testreactivenetwork.setText(connectivityStatus.toString());
                    }
                });
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    public void initFile() {
        File file = new File(rootPath);
        if (!file.exists()) {
            file.mkdirs();

        }

    }


    public void initHttp() {
        Retrofit restAdapter = new Retrofit.Builder().baseUrl(API)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();
//        restAdapter.client().setConnectTimeout(10, TimeUnit.MINUTES);
//        restAdapter.client().setReadTimeout(10, TimeUnit.MINUTES);
//        restAdapter.client().setWriteTimeout(10, TimeUnit.MINUTES);
        restAdapter.client().interceptors().add(new LoggingInterceptor());//拦截器
        // creating a service for adapter with our GET class
        httpService = restAdapter.create(HttpService.class);
    }

    public void initCarParamHttp() {
        Retrofit restAdapter = new Retrofit.Builder().baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();
//        restAdapter.client().setConnectTimeout(10, TimeUnit.MINUTES);
//        restAdapter.client().setReadTimeout(10, TimeUnit.MINUTES);
//        restAdapter.client().setWriteTimeout(10, TimeUnit.MINUTES);
        restAdapter.client().interceptors().add(new LoggingInterceptor());//拦截器
        // creating a service for adapter with our GET class
        CarParamhttpService = restAdapter.create(HttpService.class);
    }

    public void initCarConfigHttp() {
        Retrofit restAdapter = new Retrofit.Builder().baseUrl(API_CAR_CONFIG)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();
        restAdapter.client().interceptors().add(new LoggingInterceptor());//拦截器
        CarConfighttpService = restAdapter.create(HttpService.class);
    }

    /**
     * 加载省份城市
     */
    public void initCityHttp() {
        Retrofit restAdapter = new Retrofit.Builder().baseUrl(CITY_API)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        restAdapter.client().interceptors().add(new LoggingInterceptor());//拦截器
//        restAdapter.client().interceptors().add(new LoggingInterceptor());
        // creating a service for adapter with our GET class

        cityHttpService = restAdapter.create(HttpService.class);
    }


    /**
     * 初始化服务器全局维护的请求地址
     * 如：品牌、车系、车型、地区
     */
    public void initGlobalHttp() {
        Retrofit restAdapter = new Retrofit.Builder().baseUrl(GLOBAL_API)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        restAdapter.client().interceptors().add(new LoggingInterceptor());//拦截器
//        restAdapter.client().interceptors().add(new LoggingInterceptor());
        // creating a service for adapter with our GET class

        globalHttpService = restAdapter.create(HttpService.class);
    }

    /**
     * 初始化CustomActivityOnCrash
     * https://github.com/Ereza/CustomActivityOnCrash
     */
//    public void CustomActivityOnCrashInit() {
//
//
//        // 官方注释-->If you already have ACRA, Crashlytics or any similar library in your app, it will still work as normal, but the CustomActivityOnCrash initialization MUST be done first, or the original reporting tool will stop working.
//        CustomActivityOnCrash.install(this);
//        /**
//         * 跳转到指定的activity,必须设置：android:process=":error_activity"，否则会跳转到默认的activity,ec
//         * <activity
//         android:name="cat.ereza.sample.customactivityoncrash.activity.CustomErrorActivity"
//         android:label="@string/error_title"
//         android:process=":error_activity" />
//         */
////        CustomActivityOnCrash.setErrorActivityClass(Class<? extends Activity>);
//        //修改默认activity的图片
////        CustomActivityOnCrash.setDefaultErrorActivityDrawable(R.mipmap.ic_launcher);
//    }
//
////    public static RefWatcher getRefWatcher(Context context) {
////        AppContext application = (AppContext) context.getApplicationContext();
////        return application.refWatcher;
////    }

    /**
     * 初始化ImageLoader initImageLoader: 使用imageload库必须加
     */
    public void initImageLoader() {
        // This configuration tuning is custom. You can tune every option, you
        // may tune some of them,
        // or you can create default configuration by
        // ImageLoaderConfiguration.createDefault(this);
        // method.
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                getApplicationContext()).threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .writeDebugLogs() // Remove for release app
                .build();
        // Initialize ImageLoader with
        // configuration.

        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.jingzhengu_moren)//设置图片在下载期间显示的图片
                .showImageForEmptyUri(R.drawable.jingzhengu_moren)//设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.jingzhengu_moren)//设置图片加载/解码过程中错误时候显示的图片
                .delayBeforeLoading(100)//设置延时多少时间后开始下载
                .cacheInMemory(true)//设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)// 设置下载的资源是否缓存在SD卡中
                .considerExifParams(true)// 是否考虑JPEG图像EXIF参数（旋转，翻转）
                .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)//设置图片以何种编码方式显示
                .bitmapConfig(Bitmap.Config.RGB_565) // 设置图片的解码类型
//                .displayer(new RoundedBitmapDisplayer(20))//是否设置为圆角，弧度为多少
//                .displayer(new FadeInBitmapDisplayer(500))//是否图片加载好后渐入的动画时间
                .build();
        ImageLoader.getInstance().init(config);
    }

    public User getUser() {
        if (user == null) {
            user = (User) ACache.get(this).getAsObject("User");
        }

        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    /**
     * 返回状态
     *
     * @return
     */
    @NonNull
    public StatusData getStatus() {
        if (ss == null) {
            ss = (StatusData) ACache.get(this).getAsObject("statusData");
        }
        return ss;
    }

    class LoggingInterceptor implements Interceptor {
        @Override
        public Response intercept(Interceptor.Chain chain) throws IOException {
            Request request = chain.request();
            Logger.e("request=" + request.url());
            // Logger.i("request="+request);
            long t1 = System.nanoTime();
            //Logger.i(String.format("Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers()));
            Response response = chain.proceed(request);
            long t2 = System.nanoTime();
            // Logger.i(String.format("Received response for %s in %.1fms%n%s", response.request().url(), (t2 - t1) / 1e6d, response.headers()));
            final String responseString = new String(response.body().bytes());
            Logger.i("Response: " + responseString);
            Logger.e("Response: " + responseString);
            return response.newBuilder().body(ResponseBody.create(response.body().contentType(), responseString)).build();
        }
    }
}